#include <iostream>
#include <memory.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << "   serverIP serverPort\n"
              << std::endl;
}

//./tcp_client targetIP targetport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket errot" << std::endl;
        exit(2);
    }

    // 不bind

    // 不listen,因为没有程序连接客户端，accept同理

    // 但一定能连接别人
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect errot" << std::endl;
        exit(3);
    }

    std::cout << "connect success" << std::endl;
    while (true)
    {
        std::string line;
        std::cout << "输入：" << std::endl;
        std::getline(std::cin, line);

        // 读写
        send(sock, line.c_str(), line.size(), 0);
        char buff[1024];
        ssize_t s = recv(sock, buff, sizeof(buff) - 1, 0);
        if (s > 0)
        {
            buff[s] = 0;
            std::cout << "server 回显： " << buff << std::endl;
        }
        else
            break;
    }
    close(sock);
    return 0;
}